package top.lixunda.commerce.gateway.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.net.URI;
import java.util.Map;

/**
 * 用于打印网关的转发信息
 *
 * @author LiXunda
 * @version time:2019/8/30 18:25
 */
@Slf4j
public class AccessLogGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().pathWithinApplication().value();
        HttpMethod method = request.getMethod();
        // 获取路由的目标URI
        URI targetUri = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);
        InetSocketAddress remoteAddress = request.getRemoteAddress();
        Map<String, String> headers = request.getHeaders().toSingleValueMap();
        Map<String, HttpCookie> cookies = request.getCookies().toSingleValueMap();
        Map<String, Object> attributes = exchange.getAttributes();
        return chain.filter(exchange.mutate().build()).then(Mono.fromRunnable(() -> {
            ServerHttpResponse response = exchange.getResponse();
            Map<String, String> responseHeaders = response.getHeaders().toSingleValueMap();
            HttpStatus statusCode = response.getStatusCode();
            log.info("");
            log.info("请求路径:{},客户端远程IP地址:{},请求方法:{},目标URI:{},响应码:{}",
                    path, remoteAddress, method, targetUri, statusCode);
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                log.info("headers   key:{} name:{} value:{}", entry.getKey(), entry.getValue());
            }
            for (Map.Entry<String, HttpCookie> entry : cookies.entrySet()) {
                log.info("cookies   key:{} name:{} value:{}", entry.getKey(), entry.getValue().getName(), entry.getValue().getValue());
            }
            for (Map.Entry<String, Object> entry : attributes.entrySet()) {
                log.info("attributes   key:{} value:{}", entry.getKey(), entry.getValue().toString());
            }

            for (Map.Entry<String, String> entry : responseHeaders.entrySet()) {
                log.info("responseHeaders   key:{} name:{} value:{}", entry.getKey(), entry.getValue());
            }
        }));
    }

    @Override
    public int getOrder() {
        return 10000;
    }
}
